package tralala.jdo;

import java.util.List;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.jdo.Transaction;

import tralala.data.Cancion;



public class CancionDAO {
	private PersistenceManager pm = null;
	private PersistenceManagerFactory pmf=null;
	private static CancionDAO cd= new CancionDAO();
	
	private CancionDAO(){
		System.out.println("Constructor CancionDAO");
		pmf = JDOHelper.getPersistenceManagerFactory("datanucleus.properties");
		pm=pmf.getPersistenceManager();
	}
	
	public static CancionDAO getInstance(){
		return cd;
	}
	
	public void almacenar(Cancion cancion){
		Transaction tx = pm.currentTransaction();
		tx.begin();
		pm.makePersistent(cancion);
		tx.commit();
	}
	
	public void eliminar(Cancion cancion){
		Transaction tx = pm.currentTransaction();
		tx.begin();
		pm.deletePersistent(cancion);
		tx.commit();
	}
	
	@SuppressWarnings("unchecked")
	public Cancion obtenerCancion(String name){
		
		Transaction tx = pm.currentTransaction();
		List<Cancion> tempSong=null;
		try{
		tx.begin();
		Query query = pm.newQuery("SELECT FROM " + Cancion.class.getName() + " WHERE nombre == '" + name + "'");
		tempSong = (List<Cancion>)query.execute();
		tx.commit();
		}
		catch(Exception ex)
		{
			System.out.println("EXCEPCION AL OBTENER LA CANCION: \n"+ ex.getMessage());
			
		}	
		//Dado que teniamos varias canciones iguales en la BD, cogemos una de ellas
		return tempSong.get(0);
	}
	
	@SuppressWarnings("unchecked")
	public List<Cancion> buscarCancion(String name){
		System.out.println("BUSCAR CANCION");
		pm.getFetchPlan().setMaxFetchDepth(3);
		Transaction tx = pm.currentTransaction();
		List<Cancion> listaCancion=null;
		try{
		tx.begin();
		Query q = pm.newQuery("SELECT FROM " + Cancion.class.getName() + " WHERE nombre == '" + name + "'");

		listaCancion=(List<Cancion>) q.execute();
		tx.commit();
		}catch(Exception ex)
		{
			System.out.println("EXCEPCION AL OBTENER LAS CANCIONES: \n"+ ex.getMessage());
			
		}
		System.out.println("La lista: "+listaCancion);
		return listaCancion; 
	}
}
